package org.aplikator.client.shared.rpc.marshaller;

import org.aplikator.client.shared.data.PrimaryKey;
import org.jboss.errai.marshalling.client.api.MarshallingSession;
import org.jboss.errai.marshalling.client.api.annotations.ClientMarshaller;
import org.jboss.errai.marshalling.client.api.annotations.ServerMarshaller;
import org.jboss.errai.marshalling.client.api.json.EJObject;
import org.jboss.errai.marshalling.client.api.json.EJValue;
import org.jboss.errai.marshalling.client.marshallers.AbstractNullableMarshaller;

@ClientMarshaller(PrimaryKey.class)
@ServerMarshaller(PrimaryKey.class)
public class PrimaryKeyMarshaller extends
		AbstractNullableMarshaller<PrimaryKey> {
	
	public PrimaryKeyMarshaller() {
		super();
	}

	/*@Override
	public Class<PrimaryKey> getTypeHandled() {
		return PrimaryKey.class;
	}*/

	@Override
	public PrimaryKey[] getEmptyArray() {
		return new PrimaryKey[0];
	}

	@Override
	public PrimaryKey doNotNullDemarshall(EJValue o, MarshallingSession ctx) {
		EJObject eObject = o.isObject();
		 if (eObject != null &&  (!eObject.get("pkValue").isNull())) {
			 String value = eObject.get("pkValue").isString().stringValue();
			 PrimaryKey pkey = new PrimaryKey(value);

			 if (DemarshallingUtils.containsAndNotNull(eObject, "tempId") &&  eObject.get("tempId").isString()!=null) {
				 pkey.setTempId(eObject.get("tempId").isString().stringValue());
			 }
			 return pkey;
		 } else return null;
	}

	@Override
	public String doNotNullMarshall(PrimaryKey o, MarshallingSession ctx) {
		StringBuilder builder = new StringBuilder("{");
		MarshallingUtils.string("pkValue", o.getSerializationString(), builder);
		if (o.getTempId() != null) {
			builder.append(',');
			MarshallingUtils.string("tempId", o.getTempId(), builder);
		}
		builder.append("}");
		return builder.toString(); 
	}
}